#coding:utf-8

import poplib,email
from email.header import decode_header
import smtplib
import time
import os,sys
import re
import base64
import threading
import thread

def accp_mail():
    host = "pop.163.com"
    username = "youremail@163.com"
    password = "yourpasswd"
    pp = poplib.POP3(host)
    pp.set_debuglevel(1)
    pp.user(username)
    pp.pass_(password)
    ret = pp.stat()
    print ret
    ret = pp.list()
    print ret
    down = pp.retr(len(ret[1]))
    pat = re.compile(r"<(.*)>")
    #i = 1
    #for line in down[1]:
    #    print str(i) + ":" + line
    #    i = i + 1
    a = down[1][19]      #From who
    pli = pat.search(a)   
    b = down[1][21]      #Subject
    try:
        c = down[1][46]
        c = base64.decodestring(c)
        c = c.decode('gb18030').encode('utf-8')
        print c
    except Exception:
        pass
    #print pli.group(1)
    #print b
    valuelist = []
    try:
        str1 = pli.group(1)
    except AttributeError:
        pass
    else: 
        if pli.group(1) != "youremail@qq.com":
            pass
        else:
            if b == "Subject: play":
                valuelist.append("play")
                valuelist.append(c)
                return valuelist
            else:
                if b == "Subject: stop":
                    valuelist.append("stop")
                    valuelist.append(c)
                    return valuelist
    pp.quit()
    valuelist.append("no")
    return valuelist
    #b = down[1][33].decode('utf-8')

def send_mail1():
    mail_to = smtplib.SMTP('smtp.163.com',25)
    mail_to.login('your email@163.com','your password')
    msg = """From: likang <youremail@163.com>
To: 李康 <youremail@qq.com>
Subject: already shutdown
"""
    mail_to.sendmail('youremail@163.com','youremail@qq.com',msg)
    mail_to.close()

def send_mail2():
    
    mail_to = smtplib.SMTP('smtp.qq.com',25)
    mail_to.login('youremail@qq.com','yourpasswd')
    msg = """From: likang <youremail@qq.com>
To:  likang<youremail@163.com>
Subject: already played
"""
    mail_to.sendmail('youremail@qq.com','youremail@163.com',msg)
    mail_to.close()

def playmusic(val):
    os.system("play /home/lk/Music/"+val+".mp3")

def stopmusic():
    threadlist = threading.enumerate()
    print threadlist
    if (len(threadlist) > 1):
        pidfile = os.popen("ps -o pid -C play")
        alist=[]
        for line in pidfile:
            alist.append(line)
        try:
            pid = alist[1].split('\n')[0]
            os.system("kill "+pid)
        except Exception:
            pass

if __name__ == '__main__':
    #time.sleep(120)
    while 1:
        time.sleep(5)
        val = accp_mail()
        print val
        if val[0] == "play":
            stopmusic()
            t = threading.Thread(target=playmusic,args=(val[1],))
            t.start()
            #os.system("play /home/lk/Music/"+val[1]+".mp3")
            send_mail2() 
        else:
            if val[0] == "stop":
                stopmusic()

